import axios from 'axios' // 引用axios
import store from '@/store'
import router from '@/router'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式

// axios 配置
axios.defaults.timeout = 60000
axios.defaults.withCredentials = true // 设置允许跨域设置cookie
axios.defaults.baseURL = '' // 这是调用数据接口
// http request 拦截器
axios.interceptors.request.use(
  config => {
    config.headers['Cache-Control'] = 'no-cache'
    // 请求头添加认证信息
    NProgress.start()
    if (store.state.userInfo) {
      config.headers.token = store.state.userInfo.token
      config.headers.bitaToken = store.state.userInfo.bitaToken
      config.headers.userId = store.state.userInfo.userId
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    // 收到返回关闭loading
    // loadingInstance.close()
    // 重定向处理
    NProgress.done()
    // if (response.headers.timeout) {
    //   window.location.href = JSON.parse(`${response.headers.timeout}`).redirectUrl
    //   return null
    // }
    // response状态码-1，或登录状态丢，跳转到登录页
    if (response.data.message && response.data.message.code === -1) {
      // 检测checkToken调用，仅清除本地token，否则跳转登录页
      if (response.config && response.config.url && response.config.url === '/gateway/business/api/checkToken') {
        store.commit('LOG_OUT')
      } else {
        store.commit('LOG_OUT')
        router.push({
          path: '/login'
        })
      }
      return
    } else if (response.data && (response.data.code === 60001 || response.data.code === 60005)) {
      store.commit('LOG_OUT')
      router.push({
        path: '/login'
      })
      return
    }
    return response
  },
  error => {
    //错误返回关闭loading
    // loadingInstance.close()
    NProgress.done()
    if (error && error.response && error.response.status === 401) {
      // 检测checkToken调用，仅清除本地token，否则跳转登录页
      if (error.response.config.url === '/gateway/business/api/checkToken' || error.response.config.url === '/gateway/business/api/category/getCategoryCount' || error.response.config.url === '/gateway/business/api/category/getCategoryCount') {
        store.commit('LOG_OUT')
      } else {
        store.commit('LOG_OUT')
        router.push({
          path: '/login'
        })
      }
      return false
    } else if (error && error.response && error.response.status === 500 && error.response.data.code === 'UnknownError') {
      return error.response
    } else {
      return Promise.reject(error.response)
    }
  })

export default axios

/**
 * fetch 请求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetch (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    },)
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}

/**
 * patch 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}

/**
 * put 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}
